package com.woyao;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.RegisterResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;
import com.woyao.core.util.TimeCountUtil;

import java.io.IOException;
import java.util.List;

import retrofit2.Call;

public class RegisterActivity extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private EditText verifyCode;
    private EditText refer_id;
    private Button register;
    private CheckBox checkBox;
    private boolean state = false;
    private ImageView backBtn;
    ProgressDialog progressDialog;

    String longitude = "0.0";
    String latitude = "0.0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true);
        this.setTitle("注册");

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        verifyCode = (EditText) findViewById(R.id.code);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        refer_id = (EditText) findViewById(R.id.refer_id);

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    state = true;
                } else {
                    state = false;
                }
            }
        });

        TextView agreeBtn = (TextView) findViewById(R.id.agreement);

        agreeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, WebviewActivity.class);
                intent.putExtra("link", "http://www.woyaooo.com/privacy.html");
                startActivity(intent);
            }
        });


        register = (Button) findViewById(R.id.register);
        register.setEnabled(false);
//        Button login = (Button)findViewById(R.id.login);
        sendCode = (Button) findViewById(R.id.sendCode);
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (username.getText().toString().trim().length() > 0 && password.getText().toString().trim().length() > 0 && verifyCode.getText().toString().trim().length() > 0) {
                    register.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_button_true));
                    register.setEnabled(true);
                } else {
                    register.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_button_true));
                    register.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkBox.isChecked()) {
                    register();
                } else {
                    Toast.makeText(RegisterActivity.this, "请同意我要合作用户协议", Toast.LENGTH_LONG).show();
                }
            }
        });
//        login.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//                Intent intent = new Intent();
//                intent.setClass(RegisterActivity.this, LoginActivity.class);
//                startActivity(intent);
//            }
//        });
        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCode();
            }
        });
    }

    private String code = null;
    private Button sendCode = null;
    private Integer userId = null;
    private final static int MAX = 60;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void sendCode() {
//        code = RandomUtil.randomNumber(6);

        EditText username = (EditText) findViewById(R.id.username);
        if (StringUtil.isNullOrEmpty(username.getText().toString())) {
            username.setError("手机号必填");
            return;
        }
        if (username.length() != 11) {
            username.setError("手机号错误");
            return;
        }
        final String usernameText = username.getText().toString().trim();
        code = usernameText.substring(2,5) + usernameText.substring(10,11);
        //
        TimeCountUtil timer = new TimeCountUtil(RegisterActivity.this, MAX * 1000, 1000, sendCode);
        timer.start();

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在发送中······");
        progressDialog.show();

        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.sendCode(usernameText, code);
                BaseResponse body;
                try {
                    body = responseCall.execute().body();
                    return body.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }

            }

            @Override
            protected void onPostExecute(final Boolean success) {

                if (success) {

                } else {
                    verifyCode.setError("验证码发送错误!");
                    //todo 测试代码

                }
                progressDialog.dismiss();
//                verifyCode.setHint(code);
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }

    private void register() {
        getCurrentLocation( RegisterActivity.this);
        if (StringUtil.isNullOrEmpty(username.getText().toString())) {
            username.setError("用户名必填");
            username.requestFocus();
            return;
        }
        final String usernameText = username.getText().toString().trim();
        if (usernameText == null || usernameText.length() != 11 || !usernameText.equals(username.getText().toString())) {
            username.setError("手机号错误");
            username.requestFocus();
            return;
        }
        if (StringUtil.isNullOrEmpty(password.getText().toString())) {
            password.setError("密码必填");
            password.requestFocus();
            return;
        }
        if (password.length() < 6) {
            password.setError("密码至少6位");
            password.requestFocus();
            return;
        }
        if (StringUtil.isNullOrEmpty(verifyCode.getText().toString())) {
            verifyCode.setError("验证码必填");
            verifyCode.requestFocus();
            return;
        }
        code = usernameText.substring(2,5) + usernameText.substring(10,11);
        if (code == null || !code.equals(verifyCode.getText().toString())) {
            verifyCode.setError("验证码错误");
            verifyCode.requestFocus();
            return;
        }

        final String passwordText = password.getText().toString();


        final String referid = refer_id.getText().toString();
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命处理中······");
        progressDialog.show();

        AsyncTask<Void, Void, Boolean> task =
                new AsyncTask<Void, Void, Boolean>() {
                    @Override
                    protected Boolean doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<RegisterResponse> call = svc.register(usernameText, passwordText,referid,longitude,latitude);
                        try {
                            RegisterResponse body = call.execute().body();
                            userId = body.getUserId();
                            return body.isSuccess();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }

                    @Override
                    protected void onPostExecute(final Boolean success) {

                        if (success) {
                            LoginActivity.setLogin(getApplication(), usernameText, userId);
                            Intent intent = new Intent();
                            intent.putExtra("from","register");
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.setClass(RegisterActivity.this, AccountActivity.class);

                            finish();
                            startActivity(intent);
                        } else {
                            password.setError("注册失败");
                            password.requestFocus();
                        }
                        progressDialog.dismiss();
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }

    public  void getCurrentLocation(Activity context) {
        LocationManager locationManager;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        String locationProvider = null;
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        }  else {
            return ;
        }
        //获取Location
        if ( ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }else{
            Location location = locationManager.getLastKnownLocation(locationProvider);
            if (location != null) {
                longitude = location.getLongitude() + "";
                latitude = location.getLatitude() + "";
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}
